package cn.ligoo.dtu.server;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.ligoo.dtu.domain.BmuMasterInfo;
import cn.ligoo.dtu.domain.BmuSlaveInfo;
import cn.ligoo.dtu.domain.DtuInfo;
import cn.ligoo.dtu.service.impl.FacadeImpl;
import cn.ligoo.util.ByteUtils;

/**
 * @author qinghua.jin@ligoo.cn
 * @version 2012
 * 
 */
public class DtuServerIoHandler extends IoHandlerAdapter {
	private static ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
			"classpath*:/spring-context.xml");
	private static FacadeImpl facade = ctx.getBean(FacadeImpl.class);
	private final Logger logger = LoggerFactory.getLogger(DtuServerIoHandler.class);
	private int dtu_info_id;

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		logger.error("......exceptionCaught:{}", cause.getMessage());
		cause.printStackTrace();
		session.close(true);
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		logger.info("......sessionCreated");
		logger.info("......session hasCode={}", session.hashCode());
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		logger.info("......messageReceived");

		if (message instanceof DtuInfo) {
			DtuInfo di = (DtuInfo) message;
			dtu_info_id = facade.getDtuInfoService().createDtuInfo(di);
			// logger.debug("The message received is [{}]\n\n", di.toString());
		} else if (message instanceof BmuMasterInfo) {
			BmuMasterInfo bmi = (BmuMasterInfo) message;
			bmi.setDtu_info_id(dtu_info_id);
			facade.getBmuMasterInfoService().createBmuMasterInfo(bmi);
			// logger.debug("The message received is [{}]\n\n", bmi.toString());
		} else if (message instanceof BmuSlaveInfo) {
			BmuSlaveInfo bsi = (BmuSlaveInfo) message;
			bsi.setDtu_info_id(dtu_info_id);
			facade.getBmuSlaveInfoService().createBmuSlaveInfo(bsi);
			// logger.debug("The message received is [{}]\n\n", bsi.toString());
		} else { // message instanceof byte[]
			byte[] bytes = (byte[]) message;
			logger.debug("byte.lenghth:{}", bytes.length);
			logger.debug("The message received is [{}]\n\n", ByteUtils.bytesToHexString(bytes));
		}
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		logger.info("......sessionIdle");
		logger.info("IDLE:{}", session.getIdleCount(status));
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		logger.info("......sessionClosed");
		logger.info("......session hasCode={}", session.hashCode());
	}
}
